package com.duowei.diandan.app;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.Log;

import java.util.Locale;


public class MyActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
    private static final String TAG = "MyActivityLifecycleCall";

    private static int mCreated;
    private static int mStarted;
    private static int mResumed;
    private static int mPaused;
    private static int mStopped;
    private static int mDestroyed;

    private OnAppCanExitListener mOnAppCanExitListener;

    public interface OnAppCanExitListener {
        void onAppCanExit();
    }

    public MyActivityLifecycleCallbacks(OnAppCanExitListener onAppCanExitListener) {
        mOnAppCanExitListener = onAppCanExitListener;
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        mCreated++;
    }

    @Override
    public void onActivityStarted(Activity activity) {
        mStarted++;
    }

    @Override
    public void onActivityResumed(Activity activity) {
        mResumed++;
    }

    @Override
    public void onActivityPaused(Activity activity) {
        mPaused++;
    }

    @Override
    public void onActivityStopped(Activity activity) {
        mStopped++;
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        mDestroyed++;

        if (isApplicationCanExit() && mOnAppCanExitListener != null) {
            mOnAppCanExitListener.onAppCanExit();
        }
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
    }

    public void log() {
        Log.d(TAG, String.format(Locale.CHINA, "log: mCreated = %d, mStarted = %d, mResumed = %d.",
                mCreated, mStarted, mResumed));

        Log.d(TAG, String.format(Locale.CHINA, "log: mPaused = %d, mStopped = %d, mDestroyed = %d.",
                mPaused, mStopped, mDestroyed));
    }

    public boolean isApplicationVisible() {
        return mStarted > mStopped;
    }

    public boolean isApplicationInForeground() {
        return mResumed > mPaused;
    }

    public boolean isApplicationCanExit() {
        return mCreated == mDestroyed;
    }
}
